<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\constant\TemplateConstant;
use app\common\controller\Alipay;
use app\common\controller\Wxpay;
use app\common\model\ViperCard as ViperCardModel;
use app\common\model\ViperUser;
use app\common\model\ViperCard as ViperCardM;
use app\common\service\FuYouPayService;
use app\common\service\TicketService;
use app\common\service\ViperCardService;
use think\Db;
use think\Exception;
use think\Model as ThinkModel;
use function AlibabaCloud\Client\envNotEmpty;


//会员列表模型
class ViperCard extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = '__QT_VIPER_CARD__';
    protected $name = 'qt_viper_card';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;

    public static function openCard($arr,$user_info)
    {
        $recharge_template_id = null;
        $month_template_id = null;
        $number_template_id = null;
        $total_number = 0;
        $give_amount = 0;
        $integral = 0;

        //多人总提成
        $is_many_people_commission = false;
        if(isset($arr['sales_person_data'])){
            $arr['sales_person_data'] = json_decode($arr['sales_person_data'],true);
        }
        if (!empty($arr['sales_person_data'])) {
            $is_many_people_commission = true;
            $sales_person_data = $arr['sales_person_data'];
            $many_people_commission =  array_sum(array_column($sales_person_data['list'],'commission'));
            $sale_id =  implode(',',array_column($sales_person_data['list'],'commission_user_id'));
            $group_id =  implode(',',array_column($sales_person_data['list'],'group_id'));
        } else {
            $sale_id = !empty($arr['sale_id']) ? $arr['sale_id'] : 0;
            $group_id = !empty($sale_id) ? Db::name('qt_users')->where('id',$sale_id)->value('group') : 0;
        }


        if ($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_DEFAULT) {
            $template = RechargeTemplate::get($arr['template_id']);
            //判断是否有返还金额
            if($template['moth'] != '0'){
                $give_amount = $template['give_amount'] / $template['moth'];
            }
            $arr['amount'] = $template['amount'];
            $arr['total_amount'] = $template['amount'];
            $arr['give_amount'] = $give_amount;
            $arr['give_total_amount'] = $give_amount;
            $arr['score'] = $template['integral'];
            $integral = $template['integral'];
            $recharge_template_id = $arr['template_id'];

        } elseif ($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_NUMBER) {
            $numberTemplate = NumberCardTemplate::get($arr['template_id']);
            $totalNumber = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id'=>$arr['template_id']])->value('number');
            $number_template_id = $arr['template_id'];
            $recharge_template_id = $arr['template_id'];
            $total_number = $totalNumber;

        } elseif ($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_MONTH) {
            $templateMonth = MonthCardTemplate::get($arr['template_id']);
            $month_template_id = $arr['template_id'];
            $total_number = '';
        } else {
            $template['amount'] = $arr['amount'];
            $template['rate'] = 0;
        }

        $salt = number_rand();
        $arr['salt'] = $salt;
        $passwd = !empty($arr['passwd']) ? $arr['passwd'] : config('default_passwd');
        $arr['passwd'] = pwd($passwd, $salt);

        Db::startTrans();
        try {
            $model = ViperCard::create($arr);
            // $op_type 操作类型  1 项目 2 商品 3 售卡 4 充值 5 次卡 6 副项 7 月卡
            $opType = 3;
            ViperUser::where(['phone' => $arr['mobile']])->update(['is_viper' => 1]);
            if ($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_AMOUNT) {
                $template_res['amount'] = $arr['amount'];
                $template_res['give_amount'] = $arr['give_amount'];
                $template_res['rate'] = 0;
                $template_res['id'] = 0;
                $template_res['name'] = '按实际金额充值';
                $cardType = '1';
            } elseif($arr['template_type']== TemplateConstant::TEMPLATE_TYPE_NUMBER){
                $template_res = $numberTemplate;
                $template_res['give_amount'] = 0;
                $cardType = '2';
                $opType = '5';
            } elseif($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_DEFAULT){
                $template_res = Db::name('qt_viper_recharge_template')->where('id', $recharge_template_id)->find();
                //判断是否有返还金额
                $give_amount = ViperCardModel::returnAmount($model->id, $arr['template_id']);
                $cardType = '1';
                $opType = '4';
            }elseif ($arr['template_type'] == TemplateConstant::TEMPLATE_TYPE_MONTH){
                $template_res = $templateMonth;
                $template_res['give_amount'] = 0;
                $cardType = '3';
                $opType = '7';
            }
            $viperCardId = $model->id;
            $insert = [
                'store_id' => $arr['store_id'],
                'viper_user_id' => '',
                'viper_card_id' => $viperCardId,
                'amount' => $template_res['amount'],
                'give_amount' => $give_amount,
                'recharge_tempid' => $template_res['id'],
                'pay_status' => '1',
                'order_no' => create_card_recharge(),
                'type' => '1',
                'card_amount' => intval($template_res['amount']) + $give_amount,
                'commission' => $is_many_people_commission == true ? $many_people_commission : $template_res['rate'],//提成
                'creater' => $arr['user_id'],//创建人
                'payee' => $arr['user_id'],//收款人
                'sale_id' => $sale_id,//销售人
                'create_time' => time(),
                'card_type' => $cardType,
                'status' => '1',
                'is_first' => '1',
                'recharge_temp_name' => $template_res['name'],
                'pay_time' => time(),
                'pay_content' => $arr['pay_content'],
                'collection_time' => time(),
                'update_time' => time(),
                'integral' => $integral,
                'group_id' => $group_id,
                'many_people_commission' => $is_many_people_commission == true ? json_encode($arr['sales_person_data'],JSON_UNESCAPED_UNICODE) : '',
            ];

            //插入日志
            $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
            //插入会员卡记录
            $viperCardItem = [
                'viper_card_id' => $model->id,
                'viper_type_id' => $arr['viper_type_id'],
                'recharge_template_id' => $recharge_template_id,
                'month_template_id' => $month_template_id,
                'number_template_id' => $number_template_id,
                'status' => '1',
                'total_number' => $total_number,//次卡数量
                'recharge_log_id' => $recharge_log_id,//次卡数量
            ];
            Db::name('qt_viper_card_item')->insert($viperCardItem);
            //插入支付方式
            $userInfo = Db::name('qt_users')->field('id,store_id')->where(['id' => $arr['user_id']])->find();

            if (!empty($arr['pay_content'])) {
                check_out_pay_all($arr['pay_content'], $recharge_log_id, $userInfo, '3',0,0,$viperCardId);
            }
            if (!empty($arr['coupon'])) { //充值赠送优惠券
                $coupon = json_decode($arr['coupon'], true);
                TicketService::sendTicket($coupon,$user_info,$model);
                $coupon_name = array_column($coupon,'name');
                Db::name('qt_viper_card_recharge_log')->where('id',$recharge_log_id)->update(['coupon_name'=>implode(',',$coupon_name)]);
            }

            //充值提成
            if ($is_many_people_commission == true) {//多人充值提成
                self::rechargeCommissionMany($arr, $recharge_log_id, $model->id,$opType,'1');
            }else {
                self::rechargeCommission($arr, $recharge_log_id, $model->id,$opType,'1');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            halt('错误：'.$e->getFile().$e->getLine().$e->getMessage());
        }
    }


    /**
     * 开卡充值提成
     * @param $params
     * @param $recharge_log_id
     * @param $viper_card_id
     * @param int $op_type 操作类型  1 项目 2 商品 3 售卡 4 充值 5 次卡 6 副项 7 月卡
     */
    public static function rechargeCommission($params, $recharge_log_id, $viper_card_id, $op_type = 3,$is_first = null)
    {
        $give_money = 0;
        switch ($params['template_type']) {
            case TemplateConstant::TEMPLATE_TYPE_DEFAULT ://会员卡
                $template = RechargeTemplate::get($params['template_id']);
                $give_money = $template['give_amount'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_NUMBER ://次卡
                $template = NumberCardTemplate::get($params['template_id']);
                break;
            case TemplateConstant::TEMPLATE_TYPE_MONTH ://月卡
                $template = MonthCardTemplate::get($params['template_id']);
                break;
            case TemplateConstant::TEMPLATE_TYPE_AMOUNT ://实际金额充值
                break;
        }
        if (!empty($template)) {
            $insert['money'] = $template['amount'];
            $insert['payment_price'] =  $template['amount'];
            $insert['give_money'] = $give_money;//赠送金额（售卡时使用）
            $insert['rale'] = $template['rate'];
            $user_group_id = Db::name('qt_users')->where(['id' => $params['sale_id']])->value('group');
            if ($user_group_id == 1) {
                $insert['commission'] = $template['rate'];//技师提成
            } else {
                $insert['receiver'] = $template['rate'];//接待提成
            }
        }else{
            $rechargeData = Db::name('qt_viper_card_recharge_log')->where(['id'=>$recharge_log_id])->find();
            $insert['money'] = $rechargeData['amount'];
            $insert['payment_price'] =  $rechargeData['amount'];
            $insert['give_money'] = $rechargeData['give_amount'];//赠送金额（售卡时使用）
            $insert['rale'] = 0;
            $insert['commission'] = 0;//技师提成
            $insert['receiver'] = 0;//接待提成
        }
        if(!empty($params['sale_id'])){
            $usersGroup = Db::name('qt_users')->where(['id'=>$params['sale_id']])->value('group');
            if($usersGroup == '1'){
                $insert['user_id'] = $params['sale_id'];//技师
            }else{
                $insert['cashier_id'] = $params['sale_id'];//接待人
            }
        }
        $insert['order_project_id'] = $recharge_log_id;//关联分订单 续卡为充值id
        $insert['is_pay'] = 2;
        $insert['type'] =  $op_type;//分类 1 项目 2 商品 3 售卡 4 充值 5 次卡 6 副项 7 月卡
        $insert['is_first'] =  $is_first;//1 首充 2 续充
        $insert['store_id'] = $params['store_id'];
        $insert['card_type_id'] = $params['viper_type_id'];//会员卡类型ID
        $insert['card_id'] = $viper_card_id;//会员卡ID
        $insert['created_time'] = time();
        $insert['updated_time'] = time();
        Db::name('qt_commission_log')->insert($insert);
    }

    /**
     * 多销售人开卡充值提成
     * @param $params
     * @param $recharge_log_id
     * @param $viper_card_id
     * @param int $op_type 操作类型  1 项目 2 商品 3 售卡 4 充值 5 次卡 6 副项 7 月卡
     */
    public static function rechargeCommissionMany($params, $recharge_log_id, $viper_card_id, $op_type = 3,$is_first = null)
    {
        $give_money = 0;
        switch ($params['template_type']) {
            case TemplateConstant::TEMPLATE_TYPE_DEFAULT ://会员卡
                $template = RechargeTemplate::get($params['template_id']);
                $give_money = $template['give_amount'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_NUMBER ://次卡
                $template = NumberCardTemplate::get($params['template_id']);
                break;
            case TemplateConstant::TEMPLATE_TYPE_MONTH ://月卡
                $template = MonthCardTemplate::get($params['template_id']);
                break;
            case TemplateConstant::TEMPLATE_TYPE_AMOUNT ://实际金额充值
                break;
        }

        //多销售人
        foreach ($params['sales_person_data']['list'] as $u_k => $u_v) {
            $insert = [];
            if (!empty($template)) {
                $insert['money'] = $u_v['achievement'];
                $insert['payment_price'] = $u_v['achievement'];
                $insert['give_money'] = $give_money;//赠送金额（售卡时使用）
                $insert['rale'] = $template['rate'];
            }else{
                $rechargeData = Db::name('qt_viper_card_recharge_log')->where(['id'=>$recharge_log_id])->find();
                $insert['money'] = $rechargeData['amount'];
                $insert['payment_price'] =  $rechargeData['amount'];
                $insert['give_money'] = $rechargeData['give_amount'];//赠送金额（售卡时使用）
                $insert['rale'] = 0;
                //$insert['commission'] = 0;//技师提成
                //$insert['receiver'] = 0;//接待提成
            }
            if ($u_v['group_id'] == 1) {
                $insert['user_id'] = $u_v['commission_user_id'];//技师
                $insert['commission'] = $u_v['commission'];//技师提成
            } else {
                $insert['cashier_id'] = $u_v['commission_user_id'];//接待人
                $insert['receiver'] = $u_v['commission'];//接待提成
            }

            $insert['order_project_id'] = $recharge_log_id;//关联分订单 续卡为充值id
            $insert['is_pay'] = 2;
            $insert['type'] =  $op_type;//分类 1 项目 2 商品 3 售卡 4 充值 5 次卡 6 副项 7 月卡
            $insert['is_first'] =  $is_first;//1 首充 2 续充
            $insert['store_id'] = $params['store_id'];
            $insert['card_type_id'] = $params['viper_type_id'];//会员卡类型ID
            $insert['card_id'] = $viper_card_id;//会员卡ID
            $insert['created_time'] = time();
            $insert['updated_time'] = time();

            Db::name('qt_commission_log')->insert($insert);

        }
    }

    public static function open_Card($store_id, $vip_type_id, $template_id, $phone, $engineer_id, $passwd, $birthday, $pay_type, $room_id,$money = 0)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];

        $rechargetemp = [];
        if($template_id == '0'){
            $rechargetemp['type'] = 0;
            $rechargetemp['integral'] = 0;
            $rechargetemp['give_amount'] = 0;
            $rechargetemp['amount'] = $money;
            $rechargetemp['rate'] = 0;
        }else{
            $rechargetemp = Viprecharegtemplate::where('id', $template_id)->find();
            if (empty($rechargetemp)) {
                $result['msg'] = '充值模板不存在';
                return $result;
            }
        }
        //$expire = $vip_type['expire_month'] * 3600;
        //$user = ViperUser::where('id', $user_id)->find();
        $salt = random_str(4);
        $passwd = pwd($passwd, $salt);
        //计算是否赠送积分
        $integral = $rechargetemp['integral'];
        $give_amount = $rechargetemp['give_amount'];
        $vipcard = array(
            'store_id' => $store_id,
            'card_no' => create_vaipcardrdersn(),
            'mobile' => $phone,
            'name' => '',
            'avatar' => '',
            'gender' =>'1',
            'viper_type_id' => $vip_type_id,
            'template_id' => $template_id,
            'birthday' => $birthday,
            'amount' => '0',
            'give_amount' => '0',
            'saler_id' => $engineer_id,
            'type' => 2,
            'passwd' => $passwd,
            'salt' => $salt,
            'status' => '1',
            'create_time' => time(),
            //'expire' => time() + $expire
        );
        $pay_sn = create_rearge_ordersn();
        $content = '会员卡开卡' . $pay_sn . '订单';
        $rechareglog = array(
            'store_id' => $store_id,
            'viper_user_id' => '',
            'amount' => $rechargetemp['amount'],
            'give_amount' => $give_amount,
            'create_time' => time(),
            'recharge_tempid' => $template_id,
            'pay_status' => '1',
            'integral' => $integral,
            'order_no' => create_rearge_ordersn(),
            'type' => '1'
        );
        $commion_log = array(
            'store_id' => $store_id,
            'user_id' => $engineer_id,
            //'cashier_id'=>$arr['saler_id'],
            'member' => '',
            'money' => $rechargetemp['amount'],
            'payment_price' => $rechargetemp['amount'],
            'commission' => $rechargetemp['amount'] * $rechargetemp['rate'] / 100,
            'give_money' => $rechargetemp['give_amount'],
            'rale' => $rechargetemp['rate'],
            'product_id' => '',
            'type' => '3',
            'pay_type' => $pay_type,
            'created_time' => time(),
            'card_type_id' => $vip_type_id,
            'room_id' => $room_id,
            'is_pay' => '1',
        );
        Db::startTrans();
        try {
            $card_id = ViperCardM::insertGetId($vipcard);
            $rechareglog['viper_card_id'] = $card_id;
            $rechid = VipRechargeLog::insertGetId($rechareglog);
            $commion_log['order_project_id'] = $rechid;
            $commion_log['product_id'] = $card_id;
            CommissionLog::create($commion_log);
            Db::commit();
            $res = true;
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            if($pay_type == 'ALIPAY'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'ALIPAY',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $pay_sn,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }elseif($pay_type == 'WECHAT'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'WECHAT',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $pay_sn,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }
            $result['recharge_order_id'] = $rechid;
            return $result;
        } else {
            $result = $e->getMessage();
            return $result;
        }

    }

    //会员卡消费的订单
    public static function getOrdersOfCard($store_id, $viper_card_id, $fields)
    {
        $list = Order::where(['store_id' => $store_id, 'viper_card_id' => $viper_card_id])->field($fields)->select();

        return $list;
    }

    //获取会员卡消费的技师
    public static function getEngineerOfCard($store_id, $viper_card_id)
    {
        $list = Order::alias('o')
            ->leftJoin('dp_qt_order_project p', 'p.order_id=o.id')
            ->leftJoin('dp_qt_users u', 'u.id=p.engineer_id')
            ->where(['o.store_id' => $store_id, 'o.viper_card_id' => $viper_card_id])
            ->field('u.id,u.real_name')
            ->select()->toArray();
        if (!empty($list)) {
            $list = array_unique($list);
            foreach ($list as $key => $item) {
                $count = Order::alias('o')
                    ->leftJoin('dp_qt_order_project p', 'p.order_id=o.id')
                    ->where(['o.store_id' => $store_id, 'o.viper_card_id' => $viper_card_id, 'engineer_id' => $item['id']])
                    ->count();
                $list[$key]['count'] = $count;
            }
        }
        return $list;
    }

    /**
     * @param $phone
     * @param $store_id
     * @return ViperCard[]|\think\Collection
     * 手机号查询会员卡
     */
    public function serch_phone($phone, $store_id)
    {
        $list = $this
            ->alias('card')
            ->leftJoin('qt_viper_type type','type.id = card.viper_type_id')
            ->where('card.mobile', 'like', '%' . $phone . '%')
            ->where('card.store_id', $store_id)
            ->where('card.status', '1')
            ->field('card.id,card.card_no,card.amount,card.viper_type_id,card.mobile,card.gender,card.birthday,card.name,type.name as viper_type_name')
            ->select();
        return $list;
    }


    /**
     * @param $phone
     * @param $store_id
     * @return ViperCard[]|\think\Collection
     * 手机号查询会员卡
     */
    public function card_info($id, $store_id)
    {
        $list = $this
            ->where('id', $id)
            ->field('id,mobile,name,card_no,amount,gender,birthday')
            ->select();
        return $list;
    }

    /**
     * @param $store_id
     * @param $viper_type_id
     * @return Viprecharegtemplate[]|\think\Collection
     */
    public function get_recharge_tem($store_id, $viper_type_id)
    {

        $list = Viprecharegtemplate
            ::where('store_id', $store_id)
            ->where('viper_type_id', $viper_type_id)
            ->column('amount,give_amount,name', 'id');
        return $list;

    }

    /**
     * @param $store_id
     * @param $viper_type_id
     * @return Viprecharegtemplate[]|\think\Collection
     */
    public function get_cardtype($store_id)
    {

        $list = ViperType
            ::where('store_id', $store_id)
            ->column('name', 'id');
        return $list;

    }

    public function recharge_do($store_id, $card_id, $pay_type = '1', $rechareg_temid, $room_id, $engineer_id,$money = 0)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
        $card = $this->where('id', $card_id)->find();
        $rechargetemp = [];
        if($rechareg_temid == '0'){
            $rechargetemp['type'] = 0;
            $rechargetemp['integral'] = 0;
            $rechargetemp['give_amount'] = 0;
            $rechargetemp['amount'] = $money;
            $rechargetemp['rate'] = 0;
        }else{
            $rechargetemp = Viprecharegtemplate::where('id', $rechareg_temid)->find();
            if (empty($card)) {
                $result['msg'] = '会员卡不存在';
                return $result;
            }
            if (empty($rechargetemp)) {
                $result['msg'] = '充值模板不存在';
                return $result;
            }
        }
        //计算是否赠送积分
        if ($rechargetemp['type'] == 1) {
            $have = VipRechargeLog::where('user_id', $card['viper_user_id'])
                ->where('viper_card_id', $card_id)
                ->where('store_id', $store_id)
                ->where('pay_status', '1')
                ->find();
            if (!empty($have)) {
                $integral = '0';
            } else {
                $integral = $rechargetemp['integral'];
            }
        } else {
            $integral = $rechargetemp['integral'];
        }
        $give_amount = $rechargetemp['give_amount'];
        $pay_sn = create_rearge_ordersn();
        $content = '会员卡充值' . $pay_sn . '订单';
        $rechareglog = array(
            'store_id' => $store_id,
            'user_id' => $card['viper_user_id'],
            'viper_card_id' => $card_id,
            'amount' => $rechargetemp['amount'],
            'give_amount' => $give_amount,
            'create_time' => time(),
            'recharge_tempid' => $rechareg_temid,
            'pay_status' => '1',
            'integral' => $integral,
            'order_no' => create_rearge_ordersn(),
            'type' => '2',
        );
        $commion_log = array(
            'store_id' => $store_id,
            'user_id' => $engineer_id,
            //'cashier_id'=>$arr['saler_id'],
            'member' => $card['viper_user_id'],
            'money' => $rechargetemp['amount'],
            'payment_price' => $rechargetemp['amount'],
            'commission' => $rechargetemp['amount'] * $rechargetemp['rate'] / 100,
            'give_money' => $rechargetemp['give_amount'],
            'rale' => $rechargetemp['rate'],
            'product_id' => $card_id,
            'type' => '4',
            'pay_type' => $pay_type,
            'created_time' => time(),
            'card_type_id' => $card['viper_type_id'],
            'room_id' => $room_id,
            'is_pay' => '1',
        );
        Db::startTrans();
        try {
            $rechid = VipRechargeLog::insertGetId($rechareglog);
            $commion_log['order_project_id'] = $rechid;
            CommissionLog::create($commion_log);
            Db::commit();
            $res = true;
        } catch (\Exception $e) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            if($pay_type == 'ALIPAY'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'ALIPAY',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $pay_sn,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }elseif($pay_type == 'WECHAT'){
                $data = [
                    'openid' => 130797265420571705,
                    'order_type' => 'WECHAT',
                    'goods_des' => '商品描述',
                    'mchnt_order_no' => $pay_sn,
                    'reserved_sub_appid' => '',
                    'notify_url' => 'web/fu_you_notify/cs2payNotify',
                ];
                $fu_you_pay = new FuYouPayService();
                $result = $fu_you_pay->cs2pay($data['openid'], $data['order_type'], $data['goods_des'], $data['mchnt_order_no'], $data['reserved_sub_appid'], $data['notify_url']);
            }
            $result['recharge_order_id'] = $rechid;
            return $result;
            //            if ($pay_type = '1') {
//                $url = 'api/notify/wx_rechare_notify_url';
//                $Wxpay = new Wxpay();
//                $res = $Wxpay->index($pay_sn, $rechargetemp['amount'], $content, '', 'scan', $url);
//                $result['data'] = $res;
//                $result['msg'] = $rechid;
//                $result['status'] = true;
//                return $result;
//            } else if ($pay_type == '2') {
//                $url = 'api/notify/alipay_rechare_notify_url';
//                $alipay = new Alipay();
//                $res = $alipay->alipay($pay_sn, $rechargetemp['amount'], $content, 'web', $url);
//                $result['data'] = $res;
//                $result['msg'] = $rechid;
//                $result['status'] = true;
//                return $result;
//            } else {
//                $result['msg'] = '错误的支付方式';
//                return $result;
//            }
        } else {
            $res['msg'] = $e->getMessage();
            return $res;
        }

    }

    public function change_cardmoney($id, $money, $check, $type, $mark, $content)
    {
        $result = ['status' => false, 'msg' => '变动类型错误', 'data' => ''];
        $card = $this->where('id', $id)->find();
        if (empty($card)) {
            $result['msg'] = '会员卡不存在';
            return $result;
        }
        if ($check == '1') {
            $after = $card['amount'] + $money;
        } else {
            $after = $card['amount'] - $money;
            if ($after < 0) {
                $result['msg'] = '账户余额不足';
                return $result;
            }
        }
        $brefore = $card['amount'];
        if ($money <= 0) {
            $result['msg'] = '错误的变动数量';
            return $result;
        }
        if (!is_numeric($money)) {
            $result['msg'] = '错误的变动数量';
            return $result;
        }
        $log = array(
            'user_id' => $card['user_id'],
            'brefore' => $brefore,
            'amount' => $money,
            'after' => $after,
            'create_time' => time(),
            'content' => $content,
            'mark' => $mark,
            'type' => $type,
        );
        try {
            Db::startTrans();
            if ($check == '1') {
                $this->where('id', $id)
                    ->inc('amount', $money)
                    ->update();
            } else {
                $this->where('id', $id)
                    ->dec('amount', $money)
                    ->update();
            }
            Db::name('qt_money_log')->insert($log);
            Db::commit();
            $res = true;
        } catch (Exception $exception) {
            Db::rollback();
            $res = false;
        }
        if ($res) {
            $result['status'] = true;
            return $result;
        } else {
            $result['msg'] = $exception->getMessage();
            return $result;
        }
    }


    /**
     * 返回会员赠送金额数值并插入到返还时间规则表中
     * @param $viperCardId
     * @param $templateId
     */
    public static function returnAmount($viperCardId, $templateId)
    {
        $amount = 0;//赠送金额
        $rechargeTemplate = Db::name('qt_viper_recharge_template')->where(['id' => $templateId])->find();
        //判断是否是首充赠送模版
        if ($rechargeTemplate['type'] == '1') {
            $recharge = Db::name('qt_viper_card_recharge_log')
                ->where([
                    'viper_card_id' => $viperCardId,
                    'recharge_tempid' => $templateId,
                    'card_type' => '1',
                    'is_revoke' => '2'
                ])->find();
            if (!empty($recharge)) {
                return $amount;
            }
        }
        //获取会员卡信息
        $cardRes = Db::name('qt_viper_card')->field('id,viper_type_id')->where(['id' => $viperCardId])->find();
        //加入会员卡返回金额数据
        $returnMoneyRule = Db::name('qt_viper_recharge_template_return')
            ->where([
                'viper_type_id' => $cardRes['viper_type_id'],
                'template_id' => $templateId
            ])->order('times asc')->select();
        if (!empty($returnMoneyRule)) {
            $i = 1;
            foreach ($returnMoneyRule as $key => $value) {
                $insert[$key]['viper_card_id'] = $viperCardId;
                $insert[$key]['template_id'] = $templateId;
                $insert[$key]['amount'] = $value['amount'];
                $insert[$key]['time'] = $value['times'];
                if ($value['times'] == '1') {//如果是第一次反直接反到余额，其他脚本返还
                    $is_return = '2';
                    $amount = $value['amount'];
                } else {
                    $is_return = '1';
                }
                $insert[$key]['is_return'] = $is_return;
                $insert[$key]['return_time'] = strtotime("+" . $i . " month");
                $insert[$key]['create_time'] = time();
                $i++;
            }
            Db::name('qt_viper_card_return')->insertAll($insert);
        }
        return $amount;
    }

    /**
     * 写资金变动记录
     *
     * @param $viper_card_id
     * @param $money
     * @param string $content
     * @param $check 变更类型 1：增加 2：减少
     * @param $flag  类型 1=账户余额 2=积分 3 赠送金额
     * @param $type 变更类型 1 充值 2 转账 3 消费
     * @param int $chock_order_id
     */
    public static function saveMoneyLog ($viper_card_id,$money,$check=1,$content='',$flag=1,$type=1,$chock_order_id=0) {

        $viper_card_data = Db::name('qt_viper_card')->where('id',$viper_card_id)->find();
        if (empty($viper_card_data)) {
            return false;
        }

        $data = [
            'viper_card_id'=>$viper_card_id,//会员编号
            'chock_order_id'=>$chock_order_id,//结账单号
            'type'=>$type,//变更类型 1 充值 2 转账 3 消费
            'money'=>$money,//变动金额
            'content'=>$content,//备注信息
            'check'=>$check,//变更类型 1：增加 2：减少
            'flag'=>$flag,//类型 1=账户余额 2=积分 3 赠送金额
            'after_money'=>$viper_card_data['amount']- $money,//变动后余额
            'create_time'=>time(),//日期
        ];
        Db::name('qt_viper_money_log')->insertAll($data);
    }

    /**
     * 获取会员消费详情
     * @param $viper_card_id
     */
    public static function getDetailList($viper_card_id,$limit,$page){
        $data = Db::name('qt_check_out_pay')
            ->field('pay.check_out_id,pay.create_time,pay.pay_money,u.real_name as cashier_name,out.order_no,c.mobile,s.name as store_name,c.card_no,type.name as viper_type_name,c.name as card_member_name,out.equipment_type')
            ->alias('pay')
            ->leftJoin('qt_viper_card c','c.id = pay.viper_card_id')
            ->leftJoin('qt_check_out out','out.id = pay.check_out_id')
            ->leftJoin('qt_users u','u.id = out.cashier_id')
            ->leftJoin('qt_store s','s.id = pay.store_id')
            ->leftJoin('qt_viper_type type','type.id = c.viper_type_id')
            ->where(['c.id'=>$viper_card_id,'c.type'=>'2'])
            ->paginate($limit);
        return $data;
    }


    /**
     * 获取会员充值详情
     * @param $viper_card_id
     */
    public static function getRechargeList($viper_card_id,$limit,$page){
        $data = Db::name('qt_viper_card_recharge_log')
            ->alias('log')
            ->field([
                'log.create_time',
                'log.card_amount',
                'u.real_name as payee_name',
                'log.card_amount',
                'log.recharge_temp_name',
                'c.mobile',
                's.name as store_name',
                'c.card_no',
                'type.name as viper_type_name',
                'c.name as card_member_name',
                'log.equipment_type',
                'log.sale_id'
            ])
            ->leftJoin('qt_viper_card c','c.id = log.viper_card_id')
            ->leftJoin('qt_users u','u.id = log.payee')
            ->leftJoin('qt_store s','s.id = log.store_id')
            ->leftJoin('qt_viper_type type','type.id = c.viper_type_id')
            ->where(['viper_card_id'=>$viper_card_id])
            ->paginate($limit)->each(function ($item){
                $item['sale_name'] = Db::name('qt_users')->where(['id'=>$item['sale_id']])->value('real_name');
                return $item;
            });
        return $data;
    }
}